package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.db.entity.ServiceComboOrder;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.entity.vo.WorkOrderAndSmartKitVO;
import com.mingqijia.gassafety.db.mapper.HistoryAlarmMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboOrderMapper;
import com.mingqijia.gassafety.shared.constant.BizTypeEnum;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.HuiShengStatusEnum;
import com.mingqijia.gassafety.shared.constant.TemplateTypeEnum;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkDeviceListRequest;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkRecordsRequest;
import com.mingqijia.gassafety.webserver.response.EquipmentRunningResponse;
import com.mingqijia.gassafety.webserver.response.OrderConditionResponse;
import com.mingqijia.gassafety.webserver.response.OrderConditionSonsResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkAlarmCountData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkAlarmCountResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkDeviceListData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkDeviceListResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkDeviceRunStatisticsData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkDeviceRunStatisticsResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordLogList;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordLogResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsList;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsResponse;
import com.mingqijia.gassafety.webserver.service.CockpitService;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.ConsoleSkAlarmService;
import com.mingqijia.gassafety.webserver.service.OrganizationService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @author solyutian
 * @date 2023/6/27 14:42
 */
@Slf4j
@Service
public class ConsoleSkAlarmServiceImpl implements ConsoleSkAlarmService {

  @Autowired
  ConsoleSkFeignClient consoleSkFeignClient;

  @Autowired
  HistoryAlarmMapper historyAlarmMapper;

  @Autowired
  CockpitService cockpitService;

  @Autowired
  WorkOrderHistoryService workOrderHistoryService;

  @Autowired
  OrganizationService organizationService;

  @Autowired
  CompanyService companyService;

  @Autowired
  private ServiceComboOrderMapper serviceComboOrderMapper;

  /**
   * 查询报警信息列表
   * @param request
   * @return
   */
  @Override
  public CommonResponse<ConsoleSkRecordsData> alarmRecords(ConsoleSkRecordsRequest request) {
    log.info("大屏查询报警信息列表请求:{}", JSONUtil.toJsonStr(request));
    ConsoleSkRecordsResponse response = consoleSkFeignClient
        .alarmSOSRecords(request);
    log.info("大屏查询报警信息列表响应:{}", JSONUtil.toJsonStr(response));
    if (!ObjectUtils.isEmpty(response) &&  response.getCode() == 0){
      List<ConsoleSkRecordsList> recordsLists = response.getData().getList();
      if (recordsLists.size() > 0) {
        //获取所有告警id
        List<String> idList = recordsLists.stream().map(ConsoleSkRecordsList::getId)
                .collect(Collectors.toList());
        log.info("获取所有告警ID:{}", JSONUtil.toJsonStr(idList));
        List<String> deviceIdList = recordsLists.stream().map(ConsoleSkRecordsList::getDeviceId)
                .collect(Collectors.toList());
        if (idList.size() > 0) {
          //根据告警id查询工单信息
          List<WorkOrderAndSmartKitVO> workOrderHistories = workOrderHistoryService
                  .selectWorkOrderAndSmartKitByRecordId(idList);
          Map<String, Integer> deviceCustTypeM = workOrderHistoryService.selectDeviceLastUseCustType(request.getSpId(), deviceIdList);
          log.info("根据告警id查询工单信息:{}", JSONUtil.toJsonStr(workOrderHistories));

          //批量查询告警记录工单信息
          QueryWrapper<ServiceComboOrder> queryWrapper = new QueryWrapper<>();
          queryWrapper.lambda().in(ServiceComboOrder::getAlarmRecordId, idList)
                  .eq(ServiceComboOrder::getIsDeleted, 0);
          List<ServiceComboOrder> comboOrders = serviceComboOrderMapper.selectList(queryWrapper);
          Map<String, ServiceComboOrder> comboOrderMap = new HashMap<>();
          List<String> orderCodes = new ArrayList<>();
          if (CollectionUtils.isNotEmpty(comboOrders)) {
            for (ServiceComboOrder comboOrder : comboOrders) {
              comboOrderMap.put(comboOrder.getAlarmRecordId(), comboOrder);
              orderCodes.add(comboOrder.getThirdOrderNo());
            }
          }

          if (!ObjectUtils.isEmpty(workOrderHistories)) {
            //拼装信息
            Map<String, WorkOrderAndSmartKitVO> workOrderMap = new HashMap<>();
            for (WorkOrderAndSmartKitVO orderHistory : workOrderHistories) {
              if (!StringUtils.isEmpty(orderHistory.getRecordId())) {
                workOrderMap.put(orderHistory.getRecordId(), orderHistory);
              }
            }
            for (ConsoleSkRecordsList record : recordsLists) {
              if (!StringUtils.isEmpty(record.getId()) && workOrderMap.containsKey(record.getId()) &&
                      null != workOrderMap.get(record.getId())) {
                WorkOrderAndSmartKitVO orderHistory = workOrderMap.get(record.getId());
                record.setCompleteTime(orderHistory.getCompleteTime());
                record.setCreatedTime(orderHistory.getCreatedAt());
                record.setIllustrate(orderHistory.getRemark());
                record.setResultDetail(orderHistory.getAppealResult());
                record.setSubsCode(orderHistory.getSubsCode());
                String companyname = companyService.getCompanyNameByOrgCode(record.getJvOrgCode());
                record.setCompanyName(companyname);
              }
              if (comboOrderMap.containsKey(record.getId())) {
                ServiceComboOrder comboOrder = comboOrderMap.get(record.getId());
                record.setServiceStatus(comboOrder.getOrderstatus());
                if (comboOrder.getOrderstatus() != null) {
                   record.setServiceStatusName(HuiShengStatusEnum.getPushTypes(comboOrder.getOrderstatus()).getName());
                }
                String orderExt = comboOrder.getThirdOrderExt();
                if (!StringUtils.isEmpty(orderExt)) {
                    JSONObject jsonObject = JSONObject.parseObject(orderExt);
                    if (jsonObject != null) {
                        record.setServiceEndTime(jsonObject.getString("serviceEndTime"));
                    }
                }
              }
              record.setOrderCustType(deviceCustTypeM.getOrDefault(record.getDeviceId(), Constants.ORDER_CUST_TYPE_PERSONAL));
            }
          }
        }
      }
      //加个字段给前端
      int pageNum = response.getData().getPageNum();
      int pageSize = response.getData().getPageSize();
      response.getData().setPage(pageNum);
      response.getData().setPage_size(pageSize);
      return CommonResponse.success(response.getData());
    }
    return CommonResponse.failure();
  }

  /**
   * 获取工单七日统计
   * @param spId
   * @return
   */
  @Override
  public CommonResponse<List<ConsoleSkRecordLogList>> alarmRecordLogList(String spId) {

    //获取燃气工单
    DateTime day = DateUtil.offsetDay(new Date(), -6);

    List<OrderConditionResponse> orderConditionResponses = cockpitService
        .orderCondition(DateUtil.format(day,"yyyy-MM-dd"),DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd"), 1);
    log.info("获取燃气工单数据日期:{} - {}",LocalDateTime.now(),day);
    log.info("获取燃气工单数据响应:{}",JSONUtil.toJsonStr(orderConditionResponses));
    //智慧厨房的报警统计
    ConsoleSkRecordLogResponse response = consoleSkFeignClient
        .alarmSOSRecordLogList(spId);
    log.info("智慧厨房工单七日统计响应:{}",JSONUtil.toJsonStr(response));

    if (orderConditionResponses.size() > 0){
      if (!ObjectUtils.isEmpty(response) && response.getCode() == 0){
        List<ConsoleSkRecordLogList> list = response.getData().getList();
        //智慧厨房的统计
        for (ConsoleSkRecordLogList data : list){
          //燃气的统计
          for (OrderConditionResponse r : orderConditionResponses){
            //日期一样的
            if (data.getAlarmDate().equals(r.getDate())){
              //不同的燃气工单类型
              List<OrderConditionSonsResponse> sonsResponses = r.getList();
              //找出类型为报警的
              for (OrderConditionSonsResponse sons : sonsResponses){
               if (String.valueOf(sons.getType()).equals(BizTypeEnum.BIZ_TYPE_2.getStatus())){
                 //设置燃气报警统计
                 data.setGasAlarmCnt(Integer.parseInt(String.valueOf(sons.getAppealNum())));
                 data.setGasCompleteCnt(Integer.parseInt(String.valueOf(sons.getCompleteNum())));
               }
              }
            }
          }
        }
      }
    }
    log.info("工单七日统计响应:{}", JSONUtil.toJsonStr(response));
    return CommonResponse.success(response.getData().getList());
  }

  /**
   * 当日告警总数
   * @param spId
   * @return
   */
  @Override
  public CommonResponse<ConsoleSkAlarmCountData> alarmCount(String spId, Integer templateType) {
    //获取燃气告警总数
    List<HistoryAlarmVo> list = new ArrayList<>();
    //要最近的设备信息，从数据库里查询，
    LatestLogListVO vo = new LatestLogListVO();
    String start = DateUtil.format(DateUtil.beginOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
    String end = DateUtil.format(DateUtil.endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
    //本身以及下级spId
    List<String> spIds = organizationService.getSpIds(spId);
    vo.setSpIds(spIds);
    vo.setTimeStart(start);
    vo.setTimeEnd(end);

    if(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == templateType){
      list = historyAlarmMapper.getVccRecord(vo);
    }else if(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == templateType) {
      list = historyAlarmMapper.getAsstRecord(vo);
    }
    Integer size = list.size();
    log.info("燃气今日告警总数:{}",size);

    ConsoleSkAlarmCountResponse response = consoleSkFeignClient
        .alarmSOSAlarmCount(spId);
    log.info("智慧厨房响应:{}",JSONUtil.toJsonStr(response));
    if (!ObjectUtils.isEmpty(response) && response.getCode() == 0){
      //获取智慧厨房告警总数
      ConsoleSkAlarmCountData data = response.getData();
      Integer todayAlarmCnt = data.getTodayAlarmCnt();
      //相加
      data.setTodayAlarmCnt(size + todayAlarmCnt);
      return CommonResponse.success(response.getData());
    }

    return CommonResponse.failure();
  }

  /**
   * 设备运行统计
   * @param spId
   * @return
   */
  @Override
  public CommonResponse<ConsoleSkDeviceRunStatisticsData> alarmDeviceRunStatistics(String spId) {
    ConsoleSkDeviceRunStatisticsResponse response = consoleSkFeignClient
        .alarmSOSDeviceRunStatistics(spId);
    log.info("智慧厨房设备运行统计:{}",JSONUtil.toJsonStr(response));

    if (!ObjectUtils.isEmpty(response) && response.getCode() == 0){
      //智慧厨房设备数量
      ConsoleSkDeviceRunStatisticsData data = response.getData();
      //设备总数
      Integer deviceCnt = data.getDeviceCnt();
      //正常设备数
      Integer normalCnt = data.getNormalCnt();
      //报警设备数
      Integer alarmCnt = data.getAlarmCnt();
      //故障设备数
      Integer faultCnt = data.getFaultCnt();
      //离线设备数
      Integer offlineCnt = data.getOfflineCnt();

      //燃气数量
      EquipmentRunningResponse equipmentRunningInfo = cockpitService.equipmentRunningInfo();
      log.info("燃气设备运行统计:{}",JSONUtil.toJsonStr(equipmentRunningInfo));
      //设备总数
      Integer count = equipmentRunningInfo.getCount();
      //正常总数
      Integer normalSum = equipmentRunningInfo.getNormalSum();
      //报警总数
      Integer warningSum = equipmentRunningInfo.getWarningSum();
      //故障总数
      Integer breakdownSum = equipmentRunningInfo.getBreakdownSum();
      //离线总数
      Integer offlineSum = equipmentRunningInfo.getOfflineSum();

      data.setDeviceCnt(deviceCnt + count);
      data.setNormalCnt(normalCnt + normalSum);
      data.setAlarmCnt(alarmCnt + warningSum);
      data.setFaultCnt(faultCnt + breakdownSum);
      data.setOfflineCnt(offlineCnt + offlineSum);

      response.setData(data);
      return CommonResponse.success(response.getData());
    }

    return CommonResponse.failure();
  }

  /**
   * 设备列表
   * @param request
   * @return
   */
  @Override
  public CommonResponse<ConsoleSkDeviceListData> alarmDeviceList(ConsoleSkDeviceListRequest request) {
    log.info("设备列表请求参数:{}",JSONUtil.toJsonStr(request));
    ConsoleSkDeviceListResponse response = consoleSkFeignClient.alarmSOSDeviceList(request);
    log.info("设备列表响应参数:{}",JSONUtil.toJsonStr(response));
    if (response.getCode() == 0){
      return CommonResponse.success(response.getData());
    }
    return CommonResponse.failure();
  }
}
